using System;
using System.Collections.Generic;
using Entitas;

public sealed class ProcessCollisionSystem : ReactiveSystem, ICleanupSystem {

    readonly Context _context;
    readonly Group _collisions;

    public ProcessCollisionSystem(Contexts contexts) : base(contexts.input) {
        _context = contexts.input;
        _collisions = _context.GetGroup(InputMatcher.Collision);
    }

    protected override Collector GetTrigger(Context context) {
        return context.CreateCollector(InputMatcher.Collision);
    }

    protected override bool Filter(Entity entity) {

        return true;
    }


    protected override void Execute(List<Entity> entities) {
        foreach(var e in entities) {
            e.collision.self.ReplaceHealth(e.collision.self.health.value - 1);
            var newHealth = e.collision.other.health.value - e.collision.self.damage.value;
            e.collision.other.ReplaceHealth(Math.Max(0, newHealth));
        }
    }

    public void Cleanup() {
        foreach(var e in _collisions.GetEntities()) {
            _context.DestroyEntity(e);
        }
    }
}
